<template>
	<view class="zuopin">
		<view class="page-content">
			<view class="title-wrap">
				<view class="title">{{ '我的作品(' + total + ')' }}</view>
				<view @tap="goCreate" class="btn">
					<image alt class="icon-img" mode="widthFix" src="/static/clone/ic_create_zuopin.png"></image>
					<text class="text">去创作</text>
				</view>
			</view>
			<view class="list">
				<view class="item" v-for="(item, index) in list" :key="index">
					<view @tap="goPlayVideo(item)" class="top">
						<image class="image" mode="aspectFill" :src="item.video_poster"></image>
					</view>
					<view @tap="openZuopinActions(item)" class="bottom">
						<view class="name u-line-1">{{ item.title }}</view>
						<view class="more">
							<image mode="widthFix" src="/static/clone/more-v.png"></image>
						</view>
					</view>
					<view @tap.stop.prevent="" class="status-wrap" v-if="item.status !== 1">
						<view class="producing" v-if="item.status === 0">
							<image mode="widthFix" src="/static/clone/ing.png"></image>
							<view class="primary">视频生成中</view>
						</view>
						<view @tap="showFailedMsg(item)" class="error" v-if="item.status === 2">
							<image mode="widthFix" src="/static/clone/error.png">
							</image>
							<view class="error">创作失败</view>
						</view>
					</view>
				</view>
			</view>
      <view class="loadmore">
        <u-empty v-if="isEmpty" icon="/static/ic_empty_list.png" text="暂无作品"></u-empty>
        <u-loadmore v-else :status="status" style="margin-top: 80rpx"></u-loadmore>
      </view>
		</view>
		<u-modal :asyncClose="true" :show="renameShow" title="重命名">
			<view class="add-resource-content">
				<view class="add-resource-form">
					<u--input
						border="surround"
						placeholder="请输入名称" shape="circle" v-model="renameForm.title"
					></u--input>
				</view>
			</view>
			<view slot="confirmButton">
				<view class="modal-action">
					<button @tap="closeRename" class="cancel-btn btn" :plain="true">取消</button>
					<button @tap="renameConfirm" class="confirm-btn btn" :loading="renameConfirmLoading"loadingText="保存中">确定</button>
				</view>
			</view>
		</u-modal>
		<u-popup @close="closeFailedMsg" mode="center" round="30rpx" :safeAreaInsetBottom="false" :show="cutFailedShow">
			<view class="user-info">
				<view class="title">
					<text>提 示</text>
					<view class="del-icon" @tap="closeFailedMsg" >
						<u-icon color="#999999" name="close" size="16"></u-icon>
					</view>
				</view>
				<view class="msg">{{ cutFailedMsg }}</view>
				<view @tap="delFailed" class="confirm">删除</view>
			</view>
		</u-popup>
    <customTabbar selected="zuopin"></customTabbar>
	</view>
</template>

<script>
import customTabbar from '@/components/customTabbar'
export default {
  components: { customTabbar },
	data() {
		return {
			listParams: {
				limit: 12,
				page: 1
			},
			list: [],
			isEmpty: false,
			status: 'loading',
			renameShow: false,
			renameConfirmLoading: false,
			renameForm: {
				id: '',
				title: ''
			},
			currentSetItem: null,
			total: 0,
			audio: null,
			cutFailedShow: false,
			cutFailedMsg: '',
      loopStatusSI: 0
		};
	},
	onPullDownRefresh() {
		this.listParams.page = 1;
		this.getList(1);
		setTimeout(function() {
			uni.stopPullDownRefresh();
		}, 1000);
	},
	onReachBottom() {
		if (this.status === 'loading') {
			this.listParams.page += 1;
			this.getList();
		}
	},
  onUnload() {
    this.stopLoopStatus()
  },
  beforeDestroy() {
    this.stopLoopStatus()
  },
	created() {
		this.status = 'loading';
		this.getList();
	},
	methods: {
		delFailed() {
			this.cutFailedShow = false;
			this.delZuopin(this.currentSetItem.id)
		},
		showFailedMsg(item) {
      this.cutFailedMsg = item.fail_reason || '视频合成失败了，点击删除按钮可删除失败的数据。'
			this.currentSetItem = item;
			this.cutFailedShow = true;
		},
    closeFailedMsg() {
      this.currentSetItem = null;
      this.cutFailedShow = false;
    },
		goCreate() {
			uni.navigateTo({
				url: '/pages/zuopin/create',
				events: {
					created: function() {
						this.getList();
					}
				}
			});
		},
    closeRename() {
      this.renameShow = false
    },
		renameConfirm() {
      if (!this.renameForm.title) {
        this.$util.message('请填写名称')
        return
      }
      this.$util.request({
        url: '/zuopin/rename',
        data: {
          id: this.renameForm.id,
          title: this.renameForm.title
        },
        loadingText: '正在保存'
      }).then(res => {
        this.renameShow = false;
        this.$util.message(res.message, true)
        this.list.forEach((item,index) => {
          if (item.id === this.renameForm.id) {
            this.list[index].title = this.renameForm.title
          }
        })
      })
		},
    delZuopin(id) {
      const that = this
      uni.showModal({
        title: '温馨提示',
        content: '确认删除此作品吗？删除后不可恢复',
        confirmColor: '#ea4679',
        success: function (ret) {
          if (ret.confirm) {
            that.$util.request({
              url: '/zuopin/del',
              data: {
                id: id
              },
              loadingText: '正在删除'
            }).then(res => {
              that.$util.message(res.message)
              that.listParams.page = 1;
              that.list = [];
              that.getList()
            })
          }
        }
      })
    },
		openZuopinActions(item) {
			var that = this;
			uni.showActionSheet({
				itemList: ['重命名', '删除'],
				success: function(res) {
          that.currentSetItem = item;
          if (res.tapIndex === 0) {
            that.renameForm.title = item.title;
            that.renameForm.id = item.id;
            that.renameShow = true
          } else {
            that.delZuopin(item.id)
          }
				}
			});
		},
    goPlayVideo(item) {
      uni.navigateTo({
        url: '/pages/common/video-play?down=1&zuopin_id=' + item.id + '&video_url=' + item.video_url + '&poster=' + item.video_poster
      });
    },
    // 启动状态轮询
    startLoopStatus() {
      this.stopLoopStatus()
      this.loopStatusSI = setInterval(() => {
        this.getListStatus()
      }, 5000)
    },
    // 停止状态轮询
    stopLoopStatus() {
      if (this.loopStatusSI) {
        clearInterval(this.loopStatusSI)
        this.loopStatusSI = 0
      }
    },
    getListStatus() {
      var ids = []
      this.list.forEach(item => {
        if (item.status === 0) {
          ids.push(item.id)
        }
      })
      if (ids.length > 0) {
        this.$util.request({
          url: '/zuopin/getStatusByIds',
          data: {
            ids: ids.join(',')
          },
          loading: false
        }).then(res => {
          res.data.forEach(item => {
            if (item.status !== 0) {
              for(var i = 0; i < this.list.length; i++) {
                if (this.list[i].id === item.id) {
                  this.list[i] = item
                }
              }
            }
          })
          this.$forceUpdate()
        })
      }
    },
		getList(isRefresh = 0) {
      if (isRefresh) {
        this.listParams.page = 1
        this.list = []
      }
      this.isEmpty = false;
      this.status = 'loading';
      this.$util.request({
        url: '/zuopin/getList',
        data: this.listParams
      }).then(res => {
        this.list = this.list.concat(res.data.list);
        this.list = this.list.map(item => {
          this.$set(item, 'playing', false);
          return item;
        });
        this.total = res.data.total;
        this.isEmpty = this.list.length === 0
        this.status = this.list.length === this.total ? 'nomore' : 'loadmore'
        this.startLoopStatus();
      }).catch(err => {
        this.status = 'nomore'
      })
		}
	},
}
</script>
<style scoped>
	@import './index.css';
</style>
